package dom4j.student;

import dom4j.TestA_DOM4J;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;

public class XMLUtils {
    public static Document getDocument(String filename){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(TestA_DOM4J.class.getClassLoader().getResourceAsStream(filename));
            return document;
        } catch (DocumentException e) {
            throw new RuntimeException("读取错误");
        }
    }

    public static void save(Document document,String filename){
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(
                    new FileWriter(TestA_DOM4J.class.getClassLoader().getResource(filename).getPath()),
                    format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
